package com.itheima.interceptor;

import cn.hutool.json.JSONUtil;

import com.google.gson.Gson;
import com.itheima.UserHolder;
import com.itheima.pojo.Result;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private Gson gson;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从请求头中获取token
        String token = request.getHeader("token");
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            UserHolder.setUserId(id);
        }catch (Exception e){
            log.info("token错误");
            //返回错误消息   // 返回结果：需要用原始的方式
//            String json = JSONUtil.toJsonStr(Result.error("NOT_LOGIN"));
            String json = gson.toJson(Result.error("NOT_LOGIN"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;//结束判断
        }
        return true; //可以进入目标方法
        // return false; // 直接返回浏览器   线程之内 数据共享 线程之间  数据隔离
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("111111111111执行完目标方法");
        UserHolder.removeFromThreaLocal();  // 如果不执行 出现内存泄露 导致内存溢出
    }

    // @Override
    // public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    //     System.out.println("111111111111数据已经显示到页面上");
    // }

}
